package com.boot.demofile.controller;


import com.boot.demofile.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@Slf4j
@RestController
public class FileController {

    @Value("${custconfig.local-path}")
    private String localPath;

    @RequestMapping("/file")
    public Object file(String path) {
        //        入参为null，赋予默认值
        if (StringUtils.isEmpty(path)) {
            File[] files = new File(localPath).listRoots();
            List<Map<String, Object>> filelist = packageFile(files);
            return new ResultVo().setcode(0).setcount(filelist.size()).setdata(filelist);
        }
        try {
            path = URLDecoder.decode(path,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.info("反解码失败：{}",path);
            e.printStackTrace();
        }
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            return new ResultVo().setcode(404);
        }

        if (file.isDirectory() && files.length != 0) {
            List<Map<String, Object>> maps = this.packageFile(files);
            return new ResultVo().setcode(0).setcount(files.length).setdata(maps);
        }
        return null;
    }

    @RequestMapping("/detail")
    public Object video(String code) {
        File file = new File(code);
        Map<String, Object> map = new HashMap<>();
        map.put("name", file.getName());
        map.put("path", file.getPath());
        map.put("date", new Date(file.lastModified()));
        map.put("url", code.replace(":",""));
        return map;
    }


    /**
     * 组装数据
     *
     * @param files
     * @return
     */
    private List<Map<String, Object>> packageFile(File[] files) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (File f : files) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", StringUtils.isEmpty(f.getName()) ? f.getAbsolutePath() : f.getName());
            map.put("type", f.getName().indexOf(".")==-1 ? "文件夹" : f.getName().substring(f.getName().lastIndexOf(".")));
            map.put("length", f.length());
            map.put("absolutePath", f.getAbsolutePath());
            map.put("parentFile", f.getParentFile());
            map.put("isFile", f.isFile());
            map.put("path", f.toPath());
            map.put("date", new Date(f.lastModified()));
            list.add(map);
        }
        return list;
    }
}
